import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tianpu_edu/Classes/Home/Model/home_fee_class.dart';
import 'package:tianpu_edu/Classes/Home/Model/home_public_lesso.dart';
import 'package:tianpu_edu/Classes/Home/Model/home_query_course.dart';
import 'package:tianpu_edu/Classes/Home/VC/home_details_page.dart';
import 'package:tianpu_edu/Classes/libs/tool_api_url.dart';
import 'package:tianpu_edu/Classes/libs/tool_color_utils.dart';
import 'package:tianpu_edu/Classes/libs/tool_navigation_utils.dart';
import 'package:tianpu_edu/Classes/libs/tool_text_utils.dart';
import '../../libs/tool_image_utils.dart';
import '../Model/home_product_info.dart';

class HomeView extends StatefulWidget {
  @override
  _HomeViewState createState() => _HomeViewState();
}

typedef errorCallBack<T> = void Function(T error);
typedef dataCallBack<T> = void Function(T success);

class _HomeViewState extends State<HomeView> {

  double _width;
  double _height;

  String _stringName = '请求';

  int _index = 0;
  ///头部模型
  List _dataList = [];
  ///数据模型
  HomeQueryCourse _homeQueryCourse;

  String _urlName = '系统';
  /// 刷新的控制类
  RefreshController _refreshController =
  RefreshController(initialRefresh: false);

  ///更新下拉
  void _onRefresh() async{
    // monitor network fetch
    _refreshController.refreshCompleted();
    setState(() {
    });
    _getHomeProductInfo();

  }
  ///更新上啦
  void _onLoading() async{
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    // items.add((items.length+1).toString());
    if(mounted)
      setState(() {

      });
    _refreshController.loadComplete();
  }

  @override
  void dispose() {
    super.dispose();
    print('移除---首页');
  }

  @override
  void initState() {
    super.initState();
    _getHomeProductInfo();
  }
  @override
  Widget build(BuildContext context) {

    _width = MediaQuery.of(context).size.width;
    _height = MediaQuery.of(context).size.height;

    TitleViewModel model = _dataList.length > 0 ? _dataList[_index] : null;

    return Stack(
      children: [
        Column(
          children: [
            _headerView(),
            Expanded(flex: 1,child: _contentView(model)),
          ],
        ),
        model == null ? Container() : buildAlign(),
      ],
    );
  }
  Widget _contentView(model){
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: WaterDropHeader(),
      footer: CustomFooter(
        builder: (BuildContext context,LoadStatus mode){
          Widget body ;
          if(mode==LoadStatus.idle){
            body =  Text("上拉加载");
          }
          else if(mode==LoadStatus.loading){
            body =  CupertinoActivityIndicator();
          }
          else if(mode == LoadStatus.failed){
            body = Text("加载失败！点击重试！");
          }
          else if(mode == LoadStatus.canLoading){
            body = Text("松手,加载更多!");
          }
          else{
            body = Text("没有更多数据了!");
          }
          return Container(
            height: 55.0,
            child: Center(child:body),
          );
        },
      ),
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: model == null ? Container() : CustomScrollView(
        // mainAxisAlignment: MainAxisAlignment.spaceAround,
        slivers: <Widget>[
          // SliverAppBar(
          //   // pinned: true,
          //   // expandedHeight: 42,
          //   backgroundColor: Colors.white,
          //   flexibleSpace: FlexibleSpaceBar(
          //     title: _headerView(),
          //   ),
          // ),
          SliverToBoxAdapter(child: Container(height: 6,)),
          _countList(model) <= 0
              ? SliverToBoxAdapter(child: Padding(
            padding: const EdgeInsets.only(top: 100),
            child: Center(child: Column(
              children: [
                loadAssetImage('zero',),
                SizedBox(height: 12,),
                Text('暂无$_urlName课 ~'),
              ],
            )),
          ),)
              : _sliverList(model),
          // SliverToBoxAdapter(child: FloatingActionButton(child: Text('xxxx'),onPressed: (){})),
        ],
      ),
    );
  }
  SliverList _sliverList(model){

    return SliverList(
      delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
          if(_urlName == '系统' && model.classData.queryData != null){
            // if(model.classData.queryData == null){return null;}
            ListData data = model.classData.queryData.pageInfo.list[index];
            return _listViewCell(image: data.image,courseClassName: data.courseClassName,
                learningNum: data.learningNum,price: data.price, saleCommodityId: data.saleCommodityId);
          }else if(_urlName == '公开'){
            if(model.classData.publicData == null){return null;}
            PromotionClassList data = model.classData.publicData.data[0].promotionClassList[index];
            return _listViewCell(image: data.image,courseClassName: data.name,
                learningNum: data.appointmentNum,price: 0,
                saleCommodityId: data.id);
          }else if(_urlName == '免费'){
            if(model.classData.feeData == null){return null;}
            ListDataFree data = model.classData.feeData.data.pageInfo.list[index];
            return _listViewCell(image: data.image,courseClassName: data.name,
                learningNum: data.learningNum,price: 0,
                saleCommodityId: data.currentDetailId);
          }
          // return _listViewCell(_homeQueryCourse != null ? _homeQueryCourse.pageInfo.list[index] : null);
          return null;
        },
        // childCount: _homeQueryCourse != null ? _homeQueryCourse.pageInfo.list.length : 0,
        // childCount: model.isData != false ? model.classData.queryData.pageInfo.list.length : 0,
        childCount: _countList(model),
      ),
    );
  }

  int _countList(TitleViewModel model){
    if(_urlName == '系统' && model.classData.queryData != null){
      return model.classData.queryData.pageInfo.list.length;
    }else if(_urlName == '公开' && model.classData.publicData != null && model.classData.publicData.data.length>0){
      return  model.classData.publicData.data[0].promotionClassList.length;
    }else if(_urlName == '免费' && model.classData.feeData != null){
      return  model.classData.feeData.data.pageInfo.list.length;
    }
    return 0;
  }

  /*课程切换*/
  Align buildAlign() {
    TitleViewModel model = _dataList[_index];

    return Align(
        alignment: Alignment.bottomRight,
        child: Container(padding: EdgeInsets.only(right: 6),
          child: Column(
            // crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              buildFloatingActionButton('系统',(){
                _urlName = '系统';
                ///默认是系统
                _getHomeQueryCourse(model.key);
              }),
              SizedBox(height: 20,),
              buildFloatingActionButton('公开',(){
                _urlName = '公开';
                _getHomePublic(model);
              }),
              SizedBox(height: 20,),
              buildFloatingActionButton('免费',(){
                _urlName = '免费';
                _getHomeFeeClass(model);
              }),
              SizedBox(height: 20,),
          ],),
        ),
      );
  }


  FloatingActionButton buildFloatingActionButton(String string,VoidCallback onPressed) {
    return FloatingActionButton(backgroundColor: mainColor,child: Text(string),onPressed: onPressed,heroTag: string,);
  }

  Widget _headerView() {
    return Column(
      children: <Widget>[
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(top: 6,bottom: 6),
          height: 50,//color: Colors.red,
         child: _dataList.length > 0 ? _listTitle()
            : TextButton(onPressed: (){}, child: Text('获取数据中。。。')),
        ),
      ],
    );
  }

  Widget _listTitle(){
    return ListView.builder(
        itemCount: _dataList.length,
        scrollDirection: Axis.horizontal,
        itemBuilder: (BuildContext context, int index){
          return InkWell(
            child: Container(
              padding: EdgeInsets.all(6),
              child: Text(_dataList[index].name,
                style: textStyle(color:_index == index
                    ?  mainColor :  Colors.black),),
            ),
            onTap: (){
              if(_index == index){return;}
              TitleViewModel model = _dataList[index];
              _index = index;
              if(_urlName == '系统'){
                if(model.classData.queryData != null){
                  setState(() {
                    _index = index;
                  });
                  return;
                } else{
                  _getHomeQueryCourse(_dataList[index].key);
                }
              } else if(_urlName == '公开'){
                if(model.classData.publicData != null){
                  setState(() {
                    _index = index;
                  });
                  return;
                } else{
                  _getHomePublic(_dataList[index]);
                }
              } else if(_urlName == '免费'){
                if(model.classData.feeData != null){
                  setState(() {
                    _index = index;
                  });
                  return;
                } else{
                  _getHomeFeeClass(_dataList[index]);
                }
              }

            },
          );
    });
  }

  Widget _listViewCell (
  {image,courseClassName,
    int learningNum,
    double price,
    int saleCommodityId}){
    double only = 12;
    return InkWell(
      onTap: (){

        NavigationUtil.pushPage(context, HomeDetailsPage(saleCommodityId));
      },
      child: Container(
        // padding: EdgeInsets.all(6),
        margin: EdgeInsets.only(left: only,right: only,top: only),
        color: Colors.white,
        child: Row(
          children: <Widget>[
            // loadAssetImageAll(image,all: 120),
            _imageUrl(image) ?? loadAssetImage('banner_one.jpg'),
            // Icon(Icons.airplay,size: 120,),
            SizedBox( width: 12,),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                SizedBox(
                  height: 8,
                ),
                Container(
                    width: _width - 180 - 12 - only*2,
                    child: Text(
                      courseClassName,
                      style: textStyle(),
                      maxLines: 2,
                    )),
                Text(
                  '${learningNum.toString()}人正在学习',
                  style: textStyle(color: Colors.grey, fontSize: 14),
                ),
                _urlName == '免费' ? Container() : Text(
                  '￥${price.toString()}',
                  style: textStyle(color: Colors.red, fontSize: 18),
                ),
                SizedBox(height: 8, ),
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget _imageUrl(String image) {
    return Image.network(image,width: 180,height: 120,fit: BoxFit.fitWidth,);
  }
  /// 免费课
  Future<void> _getHomeFeeClass(TitleViewModel model) async {
    ApiUrl.getHomeFeeClass(null, _dataList[_index].key, (success) {
      HomeFeeClass fee = HomeFeeClass.fromJson(success);
      setState(() {
        model.classData.feeData = fee;
      });

    }, (error) { });
  }
  /// 公开课
  Future<void> _getHomePublic(TitleViewModel model)async {
    ApiUrl.getHomePublic(null, _dataList[_index].key, (success) {
      HomePublicLesso public = HomePublicLesso.fromJson(success);
      setState(() {
        model.classData.publicData = public;
      });
    }, (error) { });
  }

  Future<void> _getHomeProductInfo() => ApiUrl.getHomeProductInfo(null, (success) {
    // LogUtil.v(success);
    HomeProductInfo homeData = HomeProductInfo.fromJson(success);
    List <FirstProducts> firstList = homeData.data.firstProducts;
    String string = '';
    List <TitleViewModel> titleModel = [];
    // firstList.forEach((element) {
    //   if(element.name != null && element.name.length > 0){
    //     // _dataList.add(element);
    //     string += element.name + ',';
    //     titleModel.add(TitleViewModel(element.name, element.key.toString()));
    //   }else{
    //     print('kong'+element.name);
    //   }
    // });

    List<SecondProducts> secondList = homeData.data.secondProducts;
    secondList.forEach((element) {
      if(element.name != null && element.name.length > 0){
      // _dataList.add(element);
      string += element.name + ',';
      titleModel.add(TitleViewModel(element.name, element.key.toString(),false));
      }else{
      print('kong'+element.name);
      }
    });

    List stringList = string.split(',');

    stringList.removeAt(stringList.length-1);

    // setState(() {
    _dataList = titleModel;
    // _getHomeQueryCourse(_dataList[_index].key);
    if(_urlName == '系统'){_getHomeQueryCourse(_dataList[_index].key);}
    else if(_urlName == '公开'){_getHomePublic(_dataList[_index]);}
    else if(_urlName == '免费'){_getHomeFeeClass(_dataList[_index]);}
    _stringName = string;
    print(_dataList);
    // });

  }, (error) { });

  Future<void> _getHomeQueryCourse(String key) async => ApiUrl.getHomeQueryCourse(null, key, (success) {
    setState(() {
      TitleViewModel model = _dataList[_index];

      _homeQueryCourse = HomeQueryCourse.fromJson(success['data']);

      model.isData = true;
      model.classData.queryData = _homeQueryCourse;
      //
      // print(_homeQueryCourse.pageInfo.list.toString());
    });
  }, (error) { });

  List<Widget> _listButton(){
    List<Widget> listWidget = [];
    if(_dataList.length > 0){
      _dataList.forEach((element) {
        listWidget.add(
            TextButton(onPressed: (){}, child: Text(element))
        );
      });
    }else{
      listWidget.add(
          TextButton(onPressed: (){}, child: Text('获取数据中。。。'))
      );
    }

    return listWidget;
  }


}

class TitleViewModel {
  final String name;
  final String key;
  bool isData = false;
  HomeQueryCourse data;// = HomeQueryCourse(pageInfo: PageInfo(list: []));
  UrlNameData classData = UrlNameData();

  TitleViewModel(this.name, this.key, this.isData,);
}

class UrlNameData{
  ///系统
  HomeQueryCourse queryData;
  ///免费
  HomeFeeClass feeData;
  ///公开
  HomePublicLesso publicData;
}

